<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="卡号/姓名/手机号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增子卡</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-wrapper">
      <el-table v-loading="loading" :data="subCardList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="sub_card_no" label="子卡号" min-width="120" />
        <el-table-column prop="name" label="持卡人" min-width="100" />
        <el-table-column prop="mobile" label="手机号" min-width="120" />
        <el-table-column prop="limit_type" label="额度类型" min-width="100">
          <template #default="{ row }">
            {{ row.limit_type === 'fixed' ? '固定额度' : '共享额度' }}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="当前余额" min-width="100">
          <template #default="{ row }">
            {{ row.balance ? formatAmount(row.balance) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleAllocateBalance(row)">分配余额</el-button>
            <el-button type="info" link @click="handleBalanceLog(row)">余额记录</el-button>
            <el-button :type="row.status ? 'danger' : 'success'" link @click="handleStatus(row)">
              {{ row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          small
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="持卡人" prop="name">
          <el-input v-model="form.name" placeholder="请输入持卡人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="额度类型" prop="limit_type">
          <el-radio-group v-model="form.limit_type">
            <el-radio label="fixed">固定额度</el-radio>
            <el-radio label="shared">共享额度</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="固定额度" prop="fixed_limit" v-if="form.limit_type === 'fixed'">
          <el-input-number v-model="form.fixed_limit" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item label="共享额度" prop="shared_limit" v-if="form.limit_type === 'shared'">
          <el-input-number v-model="form.shared_limit" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item label="单次限额" prop="single_limit">
          <el-input-number v-model="form.single_limit" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item label="日限额" prop="day_limit">
          <el-input-number v-model="form.day_limit" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item label="月限额" prop="month_limit">
          <el-input-number v-model="form.month_limit" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配余额弹窗 -->
    <el-dialog
      title="分配余额"
      v-model="balanceDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form ref="balanceFormRef" :model="balanceForm" :rules="balanceRules" label-width="100px">
        <el-form-item label="子卡号">
          <span>{{ currentCard?.sub_card_no }}</span>
        </el-form-item>
        <el-form-item label="持卡人">
          <span>{{ currentCard?.name }}</span>
        </el-form-item>
        <el-form-item label="当前余额">
          <span>{{ currentCard?.balance ? formatAmount(currentCard.balance) : '0.00' }}</span>
        </el-form-item>
        <el-form-item label="分配金额" prop="amount">
          <el-input-number v-model="balanceForm.amount" :min="0" :precision="2" :step="100" style="width: 200px" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="balanceForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="balanceDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleBalanceSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 余额记录弹窗 -->
    <el-dialog
      title="余额分配记录"
      v-model="logDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-table v-loading="logLoading" :data="balanceLogList" border>
        <el-table-column type="index" label="#" width="50" align="center" />
        <el-table-column prop="amount" label="分配金额" min-width="100">
          <template #default="{ row }">
            {{ formatAmount(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="before_balance" label="分配前余额" min-width="100">
          <template #default="{ row }">
            {{ formatAmount(row.before_balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="after_balance" label="分配后余额" min-width="100">
          <template #default="{ row }">
            {{ formatAmount(row.after_balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="operator_name" label="操作人" min-width="100" />
        <el-table-column prop="created_at" label="操作时间" min-width="160" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  status: ''
})

// 数据列表
const loading = ref(false)
const subCardList = ref([])
const total = ref(0)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  sub_card_id: undefined,
  name: '',
  mobile: '',
  limit_type: 'fixed',
  fixed_limit: 0,
  shared_limit: 0,
  single_limit: 0,
  day_limit: 0,
  month_limit: 0,
  remark: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入持卡人姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  limit_type: [{ required: true, message: '请选择额度类型', trigger: 'change' }]
}

// 余额分配相关
const balanceDialogVisible = ref(false)
const balanceFormRef = ref()
const currentCard = ref(null)
const balanceForm = reactive({
  sub_card_id: undefined,
  amount: 0,
  remark: ''
})

// 余额分配表单校验规则
const balanceRules = {
  amount: [
    { required: true, message: '请输入分配金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '分配金额必须大于0', trigger: 'blur' }
  ]
}

// 余额记录相关
const logDialogVisible = ref(false)
const logLoading = ref(false)
const balanceLogList = ref([])

// 获取子卡列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/admin/black-card-sub/list', { params: queryParams })
    subCardList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取子卡列表失败:', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = ''
  handleSearch()
}

// 新增子卡
const handleAdd = () => {
  dialogTitle.value = '新增子卡'
  form.sub_card_id = undefined
  form.name = ''
  form.mobile = ''
  form.limit_type = 'fixed'
  form.fixed_limit = 0
  form.shared_limit = 0
  form.single_limit = 0
  form.day_limit = 0
  form.month_limit = 0
  form.remark = ''
  dialogVisible.value = true
}

// 编辑子卡
const handleEdit = (row) => {
  dialogTitle.value = '编辑子卡'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    try {
      const url = form.sub_card_id ? '/admin/black-card-sub/update' : '/admin/black-card-sub/create'
      await request.post(url, form)
      ElMessage.success(form.sub_card_id ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

// 删除子卡
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该子卡吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await request.post('/admin/black-card-sub/delete', { sub_card_id: row.sub_card_id })
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 更新状态
const handleStatus = async (row) => {
  try {
    await request.post('/admin/black-card-sub/status', {
      sub_card_id: row.sub_card_id,
      status: row.status ? 0 : 1
    })
    ElMessage.success('状态更新成功')
    getList()
  } catch (error) {
    console.error('状态更新失败:', error)
  }
}

// 分配余额
const handleAllocateBalance = (row) => {
  currentCard.value = row
  balanceForm.sub_card_id = row.sub_card_id
  balanceForm.amount = 0
  balanceForm.remark = ''
  balanceDialogVisible.value = true
}

// 提交余额分配
const handleBalanceSubmit = () => {
  balanceFormRef.value?.validate(async (valid) => {
    if (!valid) return

    try {
      await request.post('/admin/black-card-sub/allocate-balance', balanceForm)
      ElMessage.success('余额分配成功')
      balanceDialogVisible.value = false
      getList()
    } catch (error) {
      console.error('余额分配失败:', error)
    }
  })
}

// 查看余额记录
const handleBalanceLog = async (row) => {
  logDialogVisible.value = true
  logLoading.value = true
  try {
    const res = await request.get('/admin/black-card-sub/balance-log', {
      params: { sub_card_id: row.sub_card_id }
    })
    balanceLogList.value = res.data.list
  } catch (error) {
    console.error('获取余额记录失败:', error)
  }
  logLoading.value = false
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 格式化金额
const formatAmount = (amount) => {
  return Number(amount).toFixed(2)
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-wrapper {
    margin-bottom: 20px;
  }

  .table-wrapper {
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 